package com.weathereport.activity;

import java.util.ArrayList;
import java.util.List;

import com.weathereport.R;
import com.weathereport.dao.WeatherDAO;
import com.weathereport.entity.Local;
import com.weathereport.entity.Forecast;
import com.weathereport.helper.Checker;
import com.weathereport.listener.GPSListener;
import com.weathereport.ws.LocalWS;
import com.weathereport.ws.WeatherWS;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class AddLocalActivity extends Activity implements OnClickListener{
	
	private EditText cityNameEditText;
	private Button addBt;
	private Button findBt;
	private Intent nav;	
	private int selectedItem;
	private LocalWS localWS;
	private List<Local> locals;
	private Local local;
	private int type;
	private String localName = null;
	private Context ctx;
	private ProgressDialog progressDialog;
	private WeatherDAO dao;
	private String[] name;
	private Handler handler = new Handler();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.addlocal);
		
		ctx = this;
		getReferences();	
		
		type = getIntent().getExtras().getInt("selectType");
		
		if (type == 0){
			findBt.setVisibility(View.VISIBLE);
			if (getIntent().hasExtra("localName")){ 
				
				localName 	= getIntent().getExtras().getString("localName");
				
				cityNameEditText.setText(localName);
				
				local = new Local();				
			}
		}
	}
	
	public void getReferences(){
		
		cityNameEditText 	= (EditText) findViewById(R.id.localNameET);				
		addBt 			= (Button) findViewById(R.id.addBT);
		addBt.setOnClickListener(this);
		findBt			= (Button) findViewById(R.id.findLocalBT);
		findBt.setOnClickListener(this);
	}

	public void onClick(View v) {
		
		if (type != 0){
			
			local = new Local();
		}
		
		switch (v.getId()) {
		case R.id.addBT:
			if (!Checker.isNullOrEmpty(cityNameEditText)){
				if (type != 0){
					
					getInfo(local);
				}else {
					
					local.setName(cityNameEditText.getText().toString());
				}
				
				saveLocal(local);
			}
						
			break;
		case R.id.findLocalBT:
			
			localWS = new LocalWS();
			locals = new ArrayList<Local>();
			
			startProgressDialog(getResources().getString(R.string.msgFindProgressTitle), getResources().getString(R.string.msgFindProgressMessage));
			
			new Thread(){
				
				public void run(){
				
					try{
									
						localWS.setCtx(ctx);
						localWS.setFindString(cityNameEditText.getText().toString());
						
						locals = localWS.getLocal(ctx, cityNameEditText.getText().toString());
										
						finishProgressDialog();
						if (locals != null){
							
							name = new String[locals.size()];
							
							for (int i = 0; i < locals.size(); i++) {
								name[i] = locals.get(i).getName();
							}
							
							Looper.prepare();
							handler.post(new Runnable() {
								
								public void run() {
									
									alertLocalsResult(ctx, name);
								}
							});								
						} else{
							Looper.prepare();
							handler.post(new Runnable() {

								public void run() {
									
									alertErrorNoLocal(ctx);
								}								
							});							
						}
					}catch (Exception e){
						
					}finally{
							
					}
				}
			}.start();
				
			break;
		default:
			break;
		}
		
	}
	
	private void saveLocal(Local localCurrent) {
				
		dao = new WeatherDAO(this);
		local = localCurrent;
		
		startProgressDialog(getResources().getString(R.string.msgAddProgressTitle), getResources().getString(R.string.msgAddProgressMessage));
		
		new Thread(){
			
			public void run(){
			
				try{
							
					if(!dao.hasLocal(local)){

						if (type == 0){
							
							localWS = new LocalWS();
							Local current = localWS.getCoordinates(ctx, localName);
						
							local.setLatitude(current.getLatitude());
							local.setLongitude(current.getLongitude());
						}
	
						List<Forecast> forecast = new ArrayList<Forecast>();
	
						WeatherWS ws = new WeatherWS();
						forecast = ws.getForecast(ctx, local);
						local.setForecast(forecast);
			
						dao.saveOrUpdateLocal(local, 0);
						
						Looper.prepare();
						handler.post(new Runnable() {

							public void run() {
								
								Toast.makeText(ctx, R.string.msgAddSuccess, Toast.LENGTH_SHORT).show();	
								goToMain();
							}								
						});				
					} else {
						
						Looper.prepare();
						handler.post(new Runnable() {

							public void run() {
								
								Toast.makeText(ctx, R.string.msgLocalExists, Toast.LENGTH_SHORT).show();			
								cityNameEditText.requestFocus();
							}
						});
					}
				}catch (Exception e){
					
				}finally{
					
					finishProgressDialog();
				}
			}
		}.start();
	}
	
	private void getInfo(Local local){
					
		local.setName(cityNameEditText.getText().toString());
		local.setLatitude(Double.toString(GPSListener.getLatitude()));
		local.setLongitude(Double.toString(GPSListener.getLongitude()));		
	}
	
	private void goToMain(){
		
		nav = new Intent(ctx, WeatheReportMain.class);
		nav.putExtra("firstRun", false);
		startActivity(nav);		
	}
	
	public void alertLocalsResult(Context ctx, String name[]) {
    			
		ArrayAdapter<CharSequence> items = new ArrayAdapter<CharSequence>(ctx, R.layout.dialoglocal,name);
		
        AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
        builder.setTitle(R.string.adgSelectLocalTitle);
        
        builder.setAdapter(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item)                   {

                selectedItem = item;
                nav = new Intent(getIntent());
            	nav.putExtra("selectType", type);
            	nav.putExtra("localName", locals.get(selectedItem).getName());
            	
            	refreshActivity(nav);
            }
        });
        
        builder.create().show();
    }
	
	public void alertErrorNoLocal(Context ctx){
		
		AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
        builder.setTitle(R.string.adgErrorLocalTitle);        
        builder.setMessage(R.string.adgErrorLocalMessage);
        builder.setNeutralButton(R.string.alertOkBT, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
            	
            	dialog.dismiss();
            }
        });
        builder.create().show();
	}
	
	private void refreshActivity(Intent intent){
		
		finish();
		startActivity(intent);		
	}
	
	protected void startProgressDialog(final String headerMessage, final String message) {
		progressDialog = ProgressDialog.show(this, headerMessage, message, false, true);
	}

	protected void finishProgressDialog() {
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
	}
}